package com.ivncorp.evnproject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.MenuItem;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.maps.android.clustering.ClusterManager;
import com.ivncorp.evnproject.map.MyItem;
import com.ivncorp.evnproject.model.UploadTable;

public class ActivityMapOnline extends FragmentActivity {
	private ClusterManager<MyItem> mClusterManager;
	private GoogleMap mMap;
	UploadTable upload;

	protected int getLayoutId() {
		return R.layout.layout_map;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(getLayoutId());
		getActionBar().setDisplayHomeAsUpEnabled(true);
		upload = (UploadTable) getIntent().getSerializableExtra("uploadtable");
		setUpMapIfNeeded();

	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getItemId() == android.R.id.home){
			finish();
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onResume() {
		super.onResume();
		setUpMapIfNeeded();
	}

	private void setUpMapIfNeeded() {
		if (mMap != null) {
			return;
		}
		mMap = ((SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map)).getMap();
		if (mMap != null) {
			startDemo();
		}
	}

	protected GoogleMap getMap() {
		setUpMapIfNeeded();
		return mMap;
	}

	protected void startDemo() {
		getMap().moveCamera(
				CameraUpdateFactory.newLatLngZoom(
						new LatLng(Double.parseDouble(upload.getLatitude()),
								Double.parseDouble(upload.getLongitude())), 10));

		mClusterManager = new ClusterManager<MyItem>(this, getMap());
		getMap().setOnCameraChangeListener(mClusterManager);
		Intent intent = getIntent();
		upload = (UploadTable) intent.getSerializableExtra("uploadtable");
		addItems();
	}

	private void addItems() {
		MyItem item = new MyItem(Double.parseDouble(upload.getLatitude()),
				Double.parseDouble(upload.getLongitude()));
		mClusterManager.addItem(item);

	}

}
